package com.flyoil.petromp.view;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.TextView;

import java.util.List;

/**
 * Created by Adminis on 2016/8/14.
 * 自定义轮播公告的控件
 */
public class LooperTextView extends FrameLayout {
    /**
     * 动画间隔
     */
    private static final int ANIM_DELAYED_MILLIONS = 5 * 1000;
    /**
     * 动画持续时长
     */
    private static final int ANIM_DURATION = 1 * 1000;
    /**
     * 默认字体颜色
     */
    private static final String DEFAULT_TEXT_COLOR = "#000000";
    /**
     * 默认字体大小  dp
     */
    private static final int DEFAULT_TEXT_SIZE = 14;
    private TextView tv_tip_out, tv_tip_in;
    /**
     * 循环播放的消息
     */
    private List<String> tipList;
    /**
     * 当前轮播到的消息索引
     */
    private int curTipIndex = 0;
    private long lastTimeMillis;

    private Handler mHandler = new Handler(Looper.getMainLooper());
    private NoticeRunnable mNoticeRunnalbe;

    private AnimationSet mEnterAnimSet;
    private AnimationSet mExitAnimSet;

    /**
     * 动画开始的一瞬间，就代表这个公告已经invisiable，下一个公告开始进入，点击事件也是给了下一个公告。
     */
    class NoticeRunnable implements Runnable {
        @Override
        public void run() {
            updateTipAndPlayAnimationWithCheck();
            mHandler.postDelayed(this, ANIM_DELAYED_MILLIONS);
        }
    }

    public LooperTextView(Context context) {
        this(context, null);
    }

    public LooperTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LooperTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initTipFrame();
        initAnimation();
    }

    /**
     * 设置item的点击事件
     */
    public void setonItemclick(OnItemClickListener onItemClickListener) {
        if (tipList == null || tipList.size() == 0) {
            return;
        }
        if (curTipIndex++ % tipList.size() == 0) {
            onItemClickListener.Onsucceed(tipList.size() - 1);
        } else {
            curTipIndex--;
            onItemClickListener.Onsucceed(curTipIndex++ % tipList.size() - 1);
        }
    }

    private void initTipFrame() {
        tv_tip_out = newTextView();
        tv_tip_in = newTextView();
        addView(tv_tip_in);
        addView(tv_tip_out);
    }

    private void createEnterAnimation() {
        mEnterAnimSet = new AnimationSet(false);
        TranslateAnimation translateAnimation =
                new TranslateAnimation(0, 0, 0, 0, TranslateAnimation.RELATIVE_TO_PARENT, 1f,
                        TranslateAnimation.RELATIVE_TO_SELF, 0f);
        AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1f);
        mEnterAnimSet.addAnimation(translateAnimation);
        mEnterAnimSet.addAnimation(alphaAnimation);
        mEnterAnimSet.setDuration(ANIM_DURATION);
    }

    private void createExitAnimation() {
        mExitAnimSet = new AnimationSet(false);
        TranslateAnimation translateAnimation =
                new TranslateAnimation(0, 0, 0, 0, TranslateAnimation.RELATIVE_TO_SELF, 0f,
                        TranslateAnimation.RELATIVE_TO_PARENT, -1f);
        AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f);
        mExitAnimSet.addAnimation(translateAnimation);
        mExitAnimSet.addAnimation(alphaAnimation);
        mExitAnimSet.setDuration(ANIM_DURATION);
    }

    /**
     * 设置要循环播放的信息
     *
     * @param tipList
     */
    public void setTipList(List<String> tipList) {
        this.tipList = tipList;
        curTipIndex = 0;
        updateTip(tv_tip_out);
        start();
    }

    /**
     * 开始循环播放公告
     * 推荐和pause()配合在生命周期中使用
     */
    public void start() {
        updateTipAndPlayAnimation();
        // 如果轮播正在运行中，不重复执行
        if (mNoticeRunnalbe == null) {
            mNoticeRunnalbe = new NoticeRunnable();
        } else {
            mHandler.removeCallbacks(mNoticeRunnalbe);
        }
        mHandler.postDelayed(mNoticeRunnalbe, ANIM_DELAYED_MILLIONS);
    }


    private void initAnimation() {
        // 初始化动画
        createExitAnimation();
        createEnterAnimation();
    }

    private void updateTipAndPlayAnimation() {
        if (curTipIndex % 2 == 0) {
            updateTip(tv_tip_out);
            tv_tip_out.setVisibility(VISIBLE);
            if (mEnterAnimSet != null) {
                tv_tip_out.startAnimation(mEnterAnimSet);
            }
            tv_tip_in.setVisibility(GONE);
            if (mExitAnimSet != null) {
                tv_tip_in.startAnimation(mExitAnimSet);
            }
//            this.bringChildToFront(tv_tip_in);
        } else {
            updateTip(tv_tip_in);

            tv_tip_in.setVisibility(VISIBLE);
            if (mEnterAnimSet != null) {
                tv_tip_in.startAnimation(mEnterAnimSet);
            }
            tv_tip_out.setVisibility(GONE);
            if (mExitAnimSet != null) {
                tv_tip_out.startAnimation(mExitAnimSet);
            }
//            this.bringChildToFront(tv_tip_out);
        }
    }

    private void updateTipAndPlayAnimationWithCheck() {
        if (System.currentTimeMillis() - lastTimeMillis < 1000) {
            return;
        }
        lastTimeMillis = System.currentTimeMillis();
        updateTipAndPlayAnimation();
    }

    private void updateTip(TextView tipView) {
//        if (new Random().nextBoolean()) {
//            tipView.setCompoundDrawables(head_boy, null, null, null);
//        } else {
//            tipView.setCompoundDrawables(head_girl, null, null, null);
//        }
        String tip = getNextTip();
        if (!TextUtils.isEmpty(tip)) {
            tipView.setText(tip);
        }
    }

    /**
     * 获取下一条消息
     *
     * @return
     */
    private String getNextTip() {
        if (isListEmpty(tipList)) return null;
        return tipList.get(curTipIndex++ % tipList.size());
    }

    private TextView newTextView() {
        TextView textView = new TextView(getContext());
        LayoutParams lp = new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, Gravity.CENTER_VERTICAL);
        textView.setLayoutParams(lp);
        textView.setGravity(Gravity.CENTER_VERTICAL);
        textView.setLines(1);
        textView.setEllipsize(TextUtils.TruncateAt.END);
        textView.setTextColor(Color.parseColor(DEFAULT_TEXT_COLOR));
        textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_TEXT_SIZE);
        return textView;
    }

//    private Animation newAnimation(float fromYValue, float toYValue) {
//        Animation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF,0,Animation.RELATIVE_TO_SELF,0,
//                Animation.RELATIVE_TO_SELF,fromYValue,Animation.RELATIVE_TO_SELF, toYValue);
//        anim.setDuration(ANIM_DURATION);
//        anim.setStartOffset(ANIM_DELAYED_MILLIONS);
//        anim.setInterpolator(new DecelerateInterpolator());
//        return anim;
//    }

    /**
     * 将资源图片转换为Drawable对象
     *
     * @param ResId
     * @return
     */
    private Drawable loadDrawable(int ResId) {
        Drawable drawable = getResources().getDrawable(ResId);
        drawable.setBounds(0, 0, drawable.getMinimumWidth() - 10, drawable.getMinimumHeight() - 10);
        return drawable;
    }

    public interface OnItemClickListener {
        public void Onsucceed(int position);
    }

    /**
     * list是否为空
     *
     * @param list
     * @return true 如果是空
     */
    public static boolean isListEmpty(List list) {
        return list == null || list.isEmpty();
    }
}
